<?php
/**
 * Mambot cbe_gmap
 * @version $Id:
 * @package 
 * @copyright Copyright (C)
 * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL
 * Nikolai Plath - www.nik-it.de
 * This is free software (like free beer ;)
 **/
 
defined( '_VALID_MOS' ) or die( 'Direct Access to this script is not allowed');

$_MAMBOTS->registerFunction( 'onPrepareContent', 'botCB_Gmap' );

function botCB_Gmap( $published, &$row  )
{

///////////////////////////////////////////////
//////// K E Y   H E R E  !!! - ja wird noch ausgelagert...///////////////
	$GMapKey = 'ABQIAAAAIvhWU2DMTj5nBDSD-hPeKRTnYtJ2ibmfHOohG9Gci_PGIWbhdBSjqPJOOp1OtWGXiVZzq9B401WNAw';
///////////////////////////////////////////////
///////////////////////////////////////////////

	$Map_Width = '600px';
	$Map_Height = '400px';
	
	define ( '_TAB_EINS_TEXT', 'Contact' );//ins Langfile
	define ( '_TAB_ZWEI_TEXT', 'Infos' );//ins Langfile
	
	
////////////////////////////////////////////////////////////////////////////////////////

//	$regex = "/{cbgmap=([^\s]*)\s*name=([^\s]*)}/s";
	$regex = "/{cbegmap}/s";

	$pos = strpos($row->text, "{cbegmap");

	if ($pos === false) {
	} else {

		preg_match ( $regex, $row->text, $BotParams );
		//print_r ($BotParams);
		global $mainframe;
	
		  global $database;
     $query = "SELECT id FROM #__mambots "
              ."WHERE element = 'cbe_gmap' "
              ."AND folder = 'content'";
     $database->setQuery( $query );
     $id = $database->loadResult();
     $mambot = new mosMambot( $database );
     $mambot->load( $id );
     $botParams = new mosParameters( $mambot->params );
     //$image = $botParams->get('image', 'globe3.png');


	$Map_Width = $botParams->get('width',$Map_Width);
	$Map_Height = $botParams->get('height',$Map_Height);


//		echo "<h1>$Map_Width KEY:".$botParams->get('googlekey','NIX')."</h1>";
		$mainframe->addCustomHeadTag( "<script src=\"http://maps.google.com/maps?file=api&amp;v=2.76&amp;key="
			.$GMapKey."\" type=\"text/javascript\"></script>");

		global $database;
		$query = "SELECT * FROM #__comprofiler";
		$database->setQuery( $query );
		$users = $database->loadObjectList();

		$selectedusers = count($users);

		if ($selectedusers > 0)
		{
			$FullEditString ='';
			$cnt=0;
			foreach($users as $user)
			{
			// CBE START
			
				$query = 

		$database->setQuery("SELECT * FROM #__comprofiler_geodata WHERE uid='".$user->user_id."'");
		$database->loadObject($U_geodata);
		//if ($database->query()) {
			//$first_load_addr_ = $first_load_addr->Geo_street." ".$first_load_addr->Geo_postcode." ".$first_load_addr
			// CBE END
				if ($U_geodata->GeoLat != '')
				{
					$cnt += 1;

					if (strpos($user->avatar, "/") === false )
					{	//custom userpic
						$cbPicPath='images/comprofiler/tn';
					} else
					{	//userpic from gallery
						$cbPicPath = 'components/com_comprofiler/images/';
					}

					if ($user->avatar == '')
					{	//user has NO avatar
						$TabEinsContent = "<strong>" . $user->firstname . " " . $user->lastname . "</strong>";
					} else
					{
						$TabEinsContent = "<img src='".$cbPicPath.$user->avatar."' alt='Image' /><br /><strong>"
						.$user->firstname." ".$user->lastname
						."</strong>";
					}
					
/*					// user Website
					$LinkString = $user->cb_website;
					$ttemp = explode ("|*|", $user->cb_website);
					$TabZweiContent = "<strong>Website:</strong><br /><a href='http://".$ttemp[0]."' target='_blank' >".$ttemp[1]."</a>";
*/

					// user GeoAddr
					$LinkString = $U_geodata->GeoAddr;
					$geoaddr_order   = array("\r\n", "\n", "\r");
					$geoaddr_replace = '<br />';
					$newstr = str_replace($geoaddr_order, $geoaddr_replace, $U_geodata->GeoAddr);
					$TabZweiContent = "<strong>GeoAdresse:</strong><br />".$newstr;//.nl2br($U_geodata->GeoAddr);


					$Markers .= "var infoTabs".$cnt." = [
					new GInfoWindowTab(\""._TAB_EINS_TEXT."\", \"".$TabEinsContent."\"),
					new GInfoWindowTab(\""._TAB_ZWEI_TEXT."\", \"".$TabZweiContent."\")
					];";
					
					//CB
//					$Markers .='
//					var posn = new GLatLng('.$user->cb_gmaplat.', '.$user->cb_gmaplon.')';
					
					//CBE
					$Markers .='
					var posn = new GLatLng('.$U_geodata->GeoLat.', '.$U_geodata->GeoLng.')';


					$Markers .="
					var marker".$cnt." = new GMarker(posn,house);
					GEvent.addListener(marker".$cnt.", 'click', function() {
					marker".$cnt.".openInfoWindowTabsHtml(infoTabs".$cnt.");
					});
					map.addOverlay(marker".$cnt.");\n";
				}
			}
		}
					
//////////////////////GET CB END


		$repl = '';
	
		// The Map "Window"
		$repl .= '<div id="gmap" style="width: ' . $Map_Width . '; height: ' . $Map_Height . '"></div>';
		
		// The Infobox
		$repl .= '<div id="gmap_infobox" align="left">Brought to you by:<br /><a href="http://www.nik-it.de">NiK-IT.de</a></div>';
		
		
		// me make the map ...
		$repl .= "<script type='text/javascript'>//<![CDATA[\n";
	
		// global var linked to div
		$repl .="var tst=document.getElementById('gmap');
				 var tstint;
				 ";
				 
		// Functions to watch if the map has changed
		$repl .= "function checkMap()
			{
				if (GBrowserIsCompatible())
				{
					if (tst)
						if (tst.offsetWidth != tst.getAttribute(\"oldValue\"))
						{
							tst.setAttribute(\"oldValue\",tst.offsetWidth);

							if (tst.getAttribute(\"refreshMap\")==0)
							if (tst.offsetWidth > 0) {
								clearInterval(tstint);
								getMap();
								tst.setAttribute(\"refreshMap\", 1);
							} 
						}
				}
			}";


		// Function for displaying the map and marker
		$repl .= "function getMap()
			{
				if (tst.offsetWidth > 0) {
				var map = new GMap2(document.getElementById('gmap'));
					";

		//The icon	
		$repl .= "
		var baseIcon = new GIcon();
          baseIcon.iconSize=new GSize(32,32);
          baseIcon.shadowSize=new GSize(56,32);
          baseIcon.iconAnchor=new GPoint(16,32);
          baseIcon.infoWindowAnchor=new GPoint(16,0);
          
	   	var house = new GIcon(baseIcon, 'http://maps.google.com/mapfiles/kml/pal3/icon56.png', null, 'http://maps.google.com/mapfiles/kml/pal3/icon56s.png');
	  	  ";
	
	//the controls
		$repl .= "map.addControl(new GLargeMapControl());
				map.addControl(new GMapTypeControl());
				map.addControl(new GOverviewMapControl());
				map.addControl(new GScaleControl());";

	//set the center
		$repl .= "map.setCenter(new GLatLng(18.979025953255267, -15.46875), 2);";
	

	//InfoBox
	$InfoBox = "var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(2,30));
      pos.apply(document.getElementById('gmap_infobox'));
      map.getContainer().appendChild(document.getElementById('gmap_infobox'));";

	$repl .= $InfoBox;
	
	$repl .= $Markers;	

	$repl .= "}
		}
		//]]></script>
		";


////Here comes the mysterious Timeoutcode for FCKNG IE #*+-
		// Call the Maps through timeout to render in IE also
		// Set an event for watching the changing of the map so it can refresh itself
	
	$repl .= "<script type=\"text/javascript\">//<![CDATA[\n";
			
	$repl .="if (GBrowserIsCompatible()) {
				tst.setAttribute(\"oldValue\",0);
				tst.setAttribute(\"refreshMap\",0);
				tstint=setInterval(\"checkMap()\",500);
			}
		//]]></script>
		";

     $row->text = preg_replace($regex, $repl, $row->text);
     return true;
  }
}  


?>